<template>
  <div class="home-wrapper">
    <router-view />
  </div>
</template>

<script>
import Scroll from '@/components/scroll/scroll'
import VHeader from '@/components/v-header/v-header'
import { isIphoneX } from '@/assets/js/brower'
import axios from '@/api/axiosApi'
import nativeBridge from '@/assets/js/nativeBridge'
import { mapGetters, mapMutations } from 'vuex'
import { getDistance } from '@/assets/js/amap'
import { handleBackMixin } from '@/assets/js/mixin'
import { localUser } from '@/assets/js/local'
import { XInput, Popup, TransferDom } from 'vux'
import { QINIU_PREFIX, AIRPLANE_H5_URL, TRAIN_H5_URL, BUS_H5_URL } from '@/api/config'
import icon from '@/assets/json/homeIcon.json'
import defaultAvatar from '@/assets/img/default_avatar.png'

// vue-awesome-swiper在全局没引入时，需要
import 'swiper/dist/css/swiper.css'
import {swiper, swiperSlide} from 'vue-awesome-swiper'

export default {
  name: 'Home',
  mixins: [handleBackMixin],
  data() {
    return {
      icon,
      recommendRate: 60,
      addressList: [],  // 目的地列表
      newPlayList: [],  // 新玩法列表
      userList: [],  // 一起嗨
      allPopupModels: ['showAtlas', 'showSearch'],
      foodCategoryRecommendList: [],
      cartEntranceShow: false,
      cityNewMethodList: [],
      activityTitleOther: [],
      cityNewMethodListContent: [],
      cityNewMethodListContentOther: [],
      cityNewMethodListContentOtherFirst: [],
      panoramaList: [],
      advertisingList: [],
      atlas: [],        // 图集
      hotelCount: 0,
      scenicCount: 0,
      featureCount: 0,
      atlasCount: 0,
      scenicFacilitiesCount: 0,
      panoramaCount: 0,
      showAtlas: false,
      showSearch: false,
      swiperOption: {
        loop: true,
        speed: 1000,
        autoplay: {
          delay: 4000
        },
        effect: 'fade',
        pagination: {
          el: '.swiper-pagination',
          bulletClass: 'top-bullet',
          bulletActiveClass: 'top-bullet-active'
        }
      },
      bannerList: [],
      defaultAvatar
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      const scrollTop = vm.$store.getters.scrollTop
      if (vm.$refs.scrollWrapper && scrollTop.Home) {
        vm.$refs.scrollWrapper.scrollTop = scrollTop.Home
        // vm.$refs.scrollWrapper.scrollTo(0, vm.$store.getters.scrollTop)
      }
    })
  },
  beforeRouteLeave (to, from, next) {
    this.$store.commit('SET_SCROLL_TOP', {Home: this.$refs.scrollWrapper.scrollTop})
    // 这里的Home可以随便命名(最好用$router.name)，但是不能重复。
    // 使用scroll组件的
    // this.$store.commit('SET_SCROLL_TOP', this.$refs.scrollWrapper.scroll.y)
    next()
  },
  directives: {
    TransferDom
  },
  components: {
    Scroll,
    XInput,
    Popup,
    VHeader,
    swiper,
    swiperSlide
  },
  computed: {
    ...mapGetters([
      'position'
    ])
  },
  created() {
    this.statusBarHeight = 24
    if (isIphoneX()) {
      this.statusBarHeight = 34
      this.paddingTop = 34
      this.atlasScrollHeight = document.body.offsetHeight - (40 + 34)
      this.paddingBottom = 24
    } else {
      this.paddingTop = 26
      this.atlasScrollHeight = window.innerHeight - (40 + 24)
    }
    this.itemWidth = (window.innerWidth - 21) / 2

    const _self = this
    this._getRecommendRate()
    this._getAddressList()
    this._getUsers()
    this.getcityNewMethodList()
    this.getactivityTitleOther()
    // 获取广告数据
    this._getAdvertising()
    this._getScenicCount()
    this._getHotelCount()
    this._getFeatureCount()
    this._getAtlasCount()
    this._getScenicFacilitiesCount()
    this._getPanoramaCount()
    this.getPanorama()
    this.getFoodCategoryRecommend()
    this._getBanner()
    nativeBridge.getPosition(this, (arg) => {
      _self.setPosition([parseFloat(arg.longitude), parseFloat(arg.latitude)])
      _self.colDistance()
    })
  },
  methods: {
    _getBanner() {
      axios.get(this, '/v1/banner/0', null, (data) => {
        data.forEach(item => {
          if (item.thumbUrl.indexOf(QINIU_PREFIX) > -1) {
            item.thumbUrl += '-w350'
          }
        })
        this.bannerList = data
      }, null, false)
    },
    _getAddressInfo() {
      // TODO 黔东南基础数据
    },
    _getAddressList() {
      axios.get(this, `/v1/address/1`, {
        pageSize: 50
      }, (data) => {
        if (data && data.length > 0) {
          this.addressList = data
          this.colDistance()
          this.$nextTick(() => {
            this.$refs.addressList.style.width = ((160 + 8) * this.addressList.length) + 'px'
          })
        }
      })
    },
    _getRecommendRate() {
      axios.get(this, `/v1/travelScore/ba062c32fdf611e7ba2d00163e0c27f8`, null, (data) => {
        this.recommendRate = data
      }, null, false)
    },
    _getNewPlayList() {
      setTimeout(() => {
        this.$refs.newPlay.style.width = (300 + 8) * this.cityNewMethodListContent.length + 'px'
      }, 200)
    },
    _getUsers() {
      axios.get(this, '/v1/recommendUser', {
        userId: localUser.get('id') || ''
      }, (data) => {
        data.forEach(item => {
          if (item.headUrl == null || item.headUrl === '') {
            item.headUrl = defaultAvatar
          }
        })
        this.userList = data
        this.$nextTick(() => {
          this.$refs.users.style.width = (87 * data.length - 10) + 'px'
        })
      })
    },
    colDistance() {
      if (this.position.length === 2 && this.addressList.length > 0) {
        let min = this.addressList[0]
        this.addressList.forEach((item, index) => {
          item.distance = getDistance(this.position, [item.longitude, item.latitude])
          if (index > 0 && item.distance < this.addressList[index - 1].distance) {
            min = item
          }
        })
        this.setCurrentArea(min)
      }
    },
    clickBanner (banner) {
      if (banner.type === 0) {
        if (banner.contentId) {
          this.$router.push(`/content/${banner.contentId}/${banner.name}`)
        }
      } else {
        if (banner.linkId) {
          const tmp = banner.linkId.split(':')
          if (tmp.length === 2) {
            switch (tmp[0]) {
              case 'scenic':
                this.$router.push(`/cart/product/${tmp[1]}/1`)
                break
              case 'hotel':
                this.$router.push(`/cart/product/${tmp[1]}/0`)
                break
              case 'feature':
                this.$router.push(`/specialLocalProductDetail/${tmp[1]}`)
                break
              case 'food':
                this.$router.push(`/foodDescribe/${tmp[1]}`)
                break
              case 'strategy':
                this.$router.push('/address/playStrategy/' + tmp[1])
                break
            }
          }
        }
      }
    },
    toAI() {
      this.$router.push('/chatAI')
    },
    selectArea(area) {
      this.setCurrentArea(area)
      this.$router.replace('/address')
    },
    ...mapMutations({
      setPosition: 'SET_POSITION',
      setAreaList: 'SET_AREA_LIST',
      setCurrentArea: 'SET_CURRENT_AREA',
      setCartTabIndex: 'SET_CART_TABINDEX'
    }),
    getFoodCategoryRecommend(recommend) {
      axios.get(this, `/v1/foodCategory`, { recommend: 1 }, (data) => {
        this.foodCategoryRecommendList = data.slice(0, 5)
      })
    },
    scrollLoadImg () {
      this.atlasPageNum++
      this._getAtlas()
    },
    mediaPicture() {
      this.showAtlas = true
      this.atlasPageNum = 1
      this._getAtlas()
    },
    cartEntranceShowClick() {
      if (this.cartEntranceShow) {
        this.$refs.toolTransform.style.transform = 'rotate(' + 0 + 'deg)'
        this.$refs.toolTransform.style.transition = 'all 0.6s ease-in-out'
      } else {
        this.$refs.toolTransform.style.transform = 'rotate(' + -180 + 'deg)'
        this.$refs.toolTransform.style.transition = 'all 0.6s ease-in-out'
      }
      this.cartEntranceShow = !this.cartEntranceShow
    },
    getcityNewMethodList() {
      axios.get(this, 'v1/activityTitle?type=0', null, (data) => {
        if (data && data.length > 0) {
          this.cityNewMethodList = data[0]
          this.getcityNewMethodListContent()
        }
      })
    },
    getactivityTitleOther() {
      axios.get(this, 'v1/activityTitle', { type: 1 }, (data) => {
        if (data && data.length > 0) {
          this.activityTitleOther = data[0]
          this.getcityNewMethodListContentOther()
        }
      })
    },
    getcityNewMethodListContent() {
      axios.get(this, `/v1/activityContent?belongActivity=${this.cityNewMethodList.id}`, null, (data) => {
        if (data && data.length > 0) {
          this.cityNewMethodListContent = data
          this._getNewPlayList()
        }
      })
    },
    getcityNewMethodListContentOther() {
      axios.get(this, `/v1/activityContent?belongActivity=${this.activityTitleOther.id}`, null, (data) => {
        if (data && data.length > 0) {
          this.cityNewMethodListContentOtherFirst = data[0]
          this.cityNewMethodListContentOther = data.slice(1)
          this.$refs.scrollRecomQiCity.style.width = (200 + 8) * this.cityNewMethodListContentOther.length + 'px'
        }
      })
    },
    getPanorama() {
      axios.get(this, '/v1/panorama', null, (data) => {
        this.panoramaList = data[0]
      })
    },
    toUSerDetail (userId) {
      this.$router.push(`/user/archives/${userId}`)
    },
    _getAdvertising() {
      axios.get(this, '/v1/advertising', null, (data) => {
        if (data && data.length > 0) {
          this.advertisingList = data[0]
        }
      }, null, false)
    },
    _getHotelCount() {
      axios.get(this, '/v1/productCount', {
        type: 0
      }, (data) => {
        this.hotelCount = data
      })
    },
    _getScenicCount() {
      axios.get(this, '/v1/productCount', {
        type: 1
      }, (data) => {
        this.scenicCount = data
      })
    },
    _getFeatureCount() {
      axios.get(this, '/v1/featureProductCount', {}, (data) => {
        this.featureCount = data
      })
    },
    _getAtlasCount() {
      axios.get(this, '/v1/scenicAtlasCount', {}, (data) => {
        this.atlasCount = data
      })
    },
    _getScenicFacilitiesCount() {
      axios.get(this, '/v1/scenicFacilitiesCount', {}, (data) => {
        this.scenicFacilitiesCount = data
      })
    },
    _getPanoramaCount() {
      axios.get(this, '/v1/panoramaCount', {}, (data) => {
        this.panoramaCount = data
      })
    },
    // 获取图集
    _getAtlas() {
      if (this.requestAtlas) {
        return
      }
      this.requestAtlas = true
      axios.get(this, `/v1/scenicAtlas`, {
        type: 1,
        pageSize: 4,
        pageNum: this.atlasPageNum
      }, (data) => {
        this.requestAtlas = false
        if (data.length === 0) {
          this.$vux.toast.text('没有更多数据了', 'middle')
          return
        }
        let tmp = []
        data.forEach(item => {
          if (item.indexOf(QINIU_PREFIX) > -1) {
            item = item + '-w200'
          }
          tmp.push({
            src: item
          })
        })
        this.atlas = this.atlas.concat(tmp)
      }, () => {
        this.requestAtlas = false
      })
    },
    preImgLoaded() {
      this.$vux.loading.hide()
    },
    previewAtlas(item, index) {
      // 预览图片
      this.$vux.loading.show({
        text: '加载中...',
        position: 'absolute'
      })
      let temp = []
      this.atlas.forEach((img, i) => {
        temp.push({
          src: img
        })
      })
      this.selectAtlas = temp
      this.$nextTick(() => {
        this.$refs.previewer.show(index)
      })
    },
    goToNewPlay(contentId) {
      this.$router.push({
        path: `/home/homeContentManagement/${contentId}`,
        query: {
          title: this.cityNewMethodList.title
        }
      })
    },
    goToQiCityPast(contentId, title) {
      this.$router.push({
        path: `/home/homeContentManagement/${contentId}`,
        query: {
          title: title || '黔城往事'
        }
      })
    },
    goToQiCityPastPanorama(id, title) {
      this.$router.push({
        path: `/home/homeContentManagement/${id}`,
        query: {
          title: title || '广告'
        }
      })
    },
    goToScenicSpot() {
      this.$router.push({
        path: '/productList/1',
        query: {
          addressInfoName: '凯里',
          addressInfoId: 'ba062c32fdf611e7ba2d00163e0c27f8'
        }
      })
    },
    goToHotel() {
      this.$router.push('/HotelQuery')
    },
    goToSpecialLocalProduct() {
      this.$router.push('/specialLocalProduct')
    },
    goToFood() {
      this.$router.push('/food')
    },
    toBus() {
      nativeBridge.openH5Page(BUS_H5_URL)
    },
    toTrain() {
      nativeBridge.openH5Page(TRAIN_H5_URL)
    },
    toAirplane() {
      nativeBridge.openH5Page(AIRPLANE_H5_URL)
    },
    goToContent (item) {
      this.$router.push(`/content/${item.contentId}/${item.name}`)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'
@import '~@/assets/css/mixins.styl'

.home-wrapper
  height 100%
  background $color-background
.scroll-wrapper
  height 100%
  -webkit-overflow-scrolling: touch;
  overflow-x hidden
  overflow-y auto
// 公共样式
.title
  position relative
  font-size $font-size-large
  color $color-text-1
  margin-bottom 15px
  font-weight 900
  no-wrap()
  .intro
    font-size 13px
    color $color-text-4
    padding-left 12px
    margin-left 9px
    border-left 1px solid $color-divider
    font-weight normal
  .more
    float right
    font-size 13px
    color $color-text-4
    padding-top 4px
    font-weight normal
.subtitle
  font-size 15px
  color #333
  margin-bottom 8px
  line-height 1
  font-weight bold
.desc
  font-size 14px
  color #999
  overflow hidden
  no-wrap()
.box
  padding 20px 15px
  background #fff
  margin-bottom $margin-bottom-module
  &:last-child
    margin-bottom 0
.horizontal-scroll
  overflow unset
// 模块样式
.top
  position relative
  width 100vw
  height 100vw
  background-repeat no-repeat
  background-size 100% 100%
  background-position center
  .recommend-rate
    position absolute
    top 34px
    right 15px
    z-index 10
    text-align center
    color #fff
    border-radius 3px
    padding 8px
    line-height 1
    background-color $color-layer
  .search
    position absolute
    top 5%
    left 50%
    z-index 10
    transform translate(-50%, -50%)
    display flex
    justify-content space-between
    align-items center
    color #fff
    border 1px solid rgba(255, 255, 255, 0.4)
    background rgba(0, 0, 0, 0.3)
    width 85%
    height 32px
    line-height 42px
    border-radius 30px
    padding 0 10px 0 18px
    margin 10px 0
    font-size 16px
    .searchLeft
      display flex
      align-items center
  .nums
    position absolute
    left 15px
    right 15px
    bottom 20px
    z-index 10
    color #fff
    font-size 16px
    .media
      display flex
      align-items center
      .item
        display flex
        align-items center
        margin-right 12px
        font-size 14px
        extend-y-click()
        div
          background $color-layer
          border-radius 50%
          width 24px
          height 24px
          line-height 30px
          text-align center
          margin-right 4px
        img
          height 12px
          margin-bottom 2px
    .product
      line-height 1
      font-size 12px
      span
        border-right 1px solid rgba(255, 255, 255, 0.6)
        padding 0 8px
        &:first-child
          padding-left 0
        &:last-child
          border-right none
    p
      margin-top 4px
  .tool
    position absolute
    right 15px
    bottom 20px
    z-index 10
    display flex
.top-swiper
  position absolute
  top 0
  left 0
  right 0
  bottom 0
  .swiper-pagination
    bottom 140px
.address-list
  position relative
  width 630px
  height 173px
  .item
    width 160px
    height 173px
    margin-right 8px
    border-radius 5px
    overflow hidden
    float left
    color #fff
    .img
      width 160px
      height 120px
      border-radius 5px
      margin-bottom 12px
      background-size cover
      background-position 50% 50%
    .bg
      width 100%
      color $color-text-1
      font-size $font-size-title
.qdn
  position relative
  z-index 2
.new-play
  .item
    background #fff
    width 300px
    height 218px
    margin-right 8px
    border-top none
    float left
    border-radius 4px
    overflow hidden
    box-shadow 0 0 12px #dfdfdf
    position relative
    z-index 1
    .img
      width 100%
      height 150px
      background-repeat no-repeat
      background-size cover
      background-position 50% 50%
    .txt
      padding 0 16px
      margin-top 12px
      margin-bottom 16px
      line-height 1.4
    .type
      width 26px
      height 26px
      position absolute
      right 10px
      bottom 50px
.users
  .item
    float left
    text-align center
    width 75px
    padding 0 6px
    img
      border 1px solid rgba(215, 215, 215, 0.8)
      border-radius 50%
    .nickname
      font-size 13px
      line-height 1
      margin-top -2px
      margin-bottom 4px
      no-wrap()
    .btn
      display inline-block
      background $color-theme
      color #fff
      line-height 21px
      height 21px
      width 56px
      border-radius 3px
      font-size 13px
      extend-click()
      &:focus, &:active, &:hover
        color $color-theme-1
    &:first-child
      padding-left 0
    &:last-child
      padding-right 0
  &:after
    content ''
    display block
    clear both
.contentWrapper
  margin-top 8px
.scrollRecom
  .recommend
    margin-right 8px
    display inline-block
    .img
      width 200px
      height 100px
      background-size cover
      background-position 50% 50%
      position relative
      box-shadow 0 0 12px #dfdfdf
      border-radius 4px
    .content
      color #fff
      position absolute
      bottom 10px
      left 10px
.qiCityPast
  .qiCityPastImg
    height 180px
    background-size cover
    background-position 50% 50%
    border-radius 4px
    overflow hidden
    position relative
    .content
      color #fff
      position absolute
      bottom 10px
      left 10px
.travels
  background #fff
  .item
    padding 15px 0
    border-bottom 0.5px solid rgba(0, 0, 0, 0.2)
    .travels-top
      display flex
      justify-content space-around
      // line-height: 1.3;
      .travels-title
        font-size $font-size-title
        font-weight bold
        min-height 40px
        no-wrap-n(3)
      .travels-desc
        margin-top 8px
        font-size $font-size-desc
        color #666
        no-wrap-n(2)
      .people
        display flex
        align-items center
        margin-top 12px
        font-size $font-size-desc
        .avatar
          width 28px
          height 28px
          border-radius 50%
        .nickname
          overflow hidden
          text-overflow ellipsis
          white-space nowrap
          max-width calc(100% - 90px)
          padding 0 6px
      .img
        height 110px
        background-size cover
        background-position center
        background-repeat no-repeat
    .travels-bottom
      display flex
      justify-content space-between
      font-size $font-size-small
      align-items center
      margin-top 9px
      .travels-type
        padding 3px 5px
        border-radius 2px
        line-height 1
        border 0.5px solid $color-theme-1
        color $color-theme-1
      .primary
        border 1px solid $color-theme
        color $color-theme

.cartEntranceWrapper
  height 0
  transition height 0.4s linear
  background #fff
  margin-bottom $margin-bottom-module
  .fadeIn, .fadeOut
    animation-duration 0.4s
    animation-delay 0.1s
.cartEntrance
  display flex
  flex-wrap wrap
  align-content flex-start
  .cartEntranceItem
    width 25%
    text-align center
    margin-top 20px
    margin-bottom 10px
    img
      display inline-block
      width 24px
      height 24px
    p
      line-height 1
      margin-top 1.5px
</style>

<style lang="stylus">
.home-wrapper
  .top-bullet
    display inline-block
    background rgba(255, 255, 255, 0.5)
    width 6px
    height 6px
    border-radius 50%
    margin-right 8px
    &:last-child
      margin-right 0
  .top-bullet-active
    background #fff
</style>
